<?php

namespace App\HttpController\Home;


use EasySwoole\ORM\DbManager;
use EasySwoole\EasySwoole\Task\TaskManager;

use App\Common\Tools;
use App\Task\CacheDel;
use App\Common\RedisCache;
use App\Model\Article\ {
    Comments,
};
use App\Common\Cache\CommentCache;

use App\Validate\Comments as CommentsValidate;

class Comment extends Base
{
    /**
     * @description: 评论
     * @param {*}
     * @return {*}
     */
    public function comment()
    {
        $result = DbManager::getInstance()->invoke(function ($client) {
            $param = $this->request()->getRequestParam();
            $errMsg = (new CommentsValidate)->validate($param, 'create');
            if ($errMsg !== true) {
                return $errMsg;
            }
            $param['ip'] = Tools::clientRealIP($this->request());
            $model = Comments::invoke($client);
            $model->createData($param, false);
            return true;
        });
        if ($result === true) {
            $task = TaskManager::getInstance();
            $args = [
                'func'  => 'afterCreate',
                'param' => $this->request()->getRequestParam()
            ];
            $call = ['call' => [new CommentCache, 'del'], 'args' => $args];
            $task->async(new CacheDel($call));
            Tools::json($this->response(), 200, [], '评论完成');
        } else {
            Tools::json($this->response(), 404, [], $result);
        }
    }
    
    /**
     * @description: 评论
     * @param {*}
     * @return {*}
     */
    public function index()
    {
        $param = $this->request()->getRequestParam();
        $param['page'] = $param['page'] ?? 1;

        $key      = 'article:' . $param['id'] .  ':comments' . ':page:' . $param['page'];
        $comments = RedisCache::get($key, function($param) {
            return DbManager::getInstance()->invoke(function ($client) use ($param) {
                $page  = $param['page'];
                $limit = 15;
                $model = Comments::invoke($client);
                $where = ['article_id' => $param['id'], 'parent_id' => 0, 'state' => 2];
    
                list($list, $total) = $model->list($page, $limit, $where);
                if ($list) {
                    $ids   = array_column($list, 'id');
                    $data  = $model->where('parent_id', $ids, 'in')->where('state', 2)
                            ->order('comment_time', 'desc')->all()->toArray();
                    $child = [];
                    foreach ($data as $val) {
                        $child[$val['parent_id']][] = $val;
                    }
                    foreach ($list as $key => $val) {
                        $val['child'] = $child[$val['id']] ?? [];
                        $list[$key]   = $val;
                    }
                }
                return Tools::page($page, $list, $total, $limit, $param);
            });
        }, $param);
        Tools::json($this->response(), 200, $comments, '查询完成');
    }
}